import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { App } from 'vue'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import { useUserStore } from '@/features/store/store'
import { setRequestRouter } from '@/request/request'
import { setComponentStoreRouter } from '@/features/store/componentStore'

const Login = () => import('@/views/Login/login.vue')
const Home = () => import('@/views/Home/home.vue')
const User = () => import('@/views/User/user.vue')
const Recycle = () => import('@/views/Recycle/recycle.vue')

// 导入的路由页面
const routeMap: { [key: string]: any } = {
  Home: Home,
  User: User,
  Recycle: Recycle,
}

const LocalNoRightRoutes: RouteRecordRaw[] = [
  { path: '/', redirect: '/home' },
  { path: '/login', name: 'Login', component: Login },
]

// @ts-ignore
const LocalRightRoutes: RouteRecordRaw[] = [
  { path: '/home', name: 'Home', component: Home },
  { path: '/user', name: 'User', component: User },
  { path: '/recycle', name: 'Recycle', component: Recycle },
]

const NotFound = () => import('@/views/NotFound/notFound.vue')
const notFound: RouteRecordRaw = {
  path: '/:catchAll(.*)*',
  name: '404',
  component: NotFound,
}

//
//
// 默认路由页面
let routes: RouteRecordRaw[] = LocalNoRightRoutes

const router = createRouter({
  // 判断是否在qiankun环境里，xxx与主应用中activeRule一致
  history: createWebHistory(
    qiankunWindow.__POWERED_BY_QIANKUN__
      ? '/subApplication/resourcePool/'
      : '/resourcePool/'
  ),
  routes,
})

// 封装路由初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router)
}
// 传递路由给axios实例使用
setRequestRouter(router)
// 传递给componentStore使用
setComponentStoreRouter(router)

//
// 提取出路由表
// @ts-ignore
const extractRoutes = (routeList: RouteItf[]): RouteRecordRaw[] => {
  if (routeList.length === 0) return []
  return formattingDataStructure(routeList)

  function formattingDataStructure(arr: RouteItf[], parentId = '') {
    const result = []
    if (arr == null || arr.length === 0) return []

    for (const item of arr) {
      if (item.parentId == parentId) {
        const children = formattingDataStructure(arr, item.id)
        if (children.length > 0) {
          result.push({
            path: item.path,
            name: item.name,
            component: routeMap[item.component],
            children: children,
          })
        } else {
          result.push({
            path: item.path,
            name: item.name,
            component: routeMap[item.component],
          })
        }
      }
    }
    return result
  }
}

//
// 路由是否进行重定向，第一次加载时进行
let routerRedirect = true
let rightRoutes: RouteRecordRaw[]
//
// @ts-ignore
// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // @ts-ignore
  const { loginStatus, remoteRoutes, getUserInfo, resetData } = useUserStore()
  rightRoutes = extractRoutes(remoteRoutes)
  // rightRoutes = LocalRightRoutes
  // console.log(rightRoutes)

  if (!loginStatus && to.path == '/login') return next()
  if (!window.localStorage.getItem('token') || to.path == '/loginRedirect') {
    // 退出时清除路由
    for (const key in rightRoutes) {
      if (router.hasRoute(rightRoutes[key].name))
        router.removeRoute(rightRoutes[key].name)
    }
    resetData()
    return next('/login')
  }

  // 当第一次加载路由时进行重定向，方便开发时使用
  if (routerRedirect && rightRoutes.length !== 0) {
    routerRedirect = false
    for (const key in rightRoutes) router.addRoute(rightRoutes[key])
    return next(to)
  }

  if (loginStatus) {
    for (const key in rightRoutes) router.addRoute(rightRoutes[key])
    router.addRoute(notFound)

    // 第一次进入系统时进行重定向
    if (to.path == '/homeRedirect') return next('/home')
    return next()
  } else {
    if (await getUserInfo()) return next(to)

    for (const key in rightRoutes) {
      if (router.hasRoute(rightRoutes[key].name))
        router.removeRoute(rightRoutes[key].name)
    }
    next('/login')
  }
})
